package com.jweb.framework.ws.client.interceptors;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ws.client.WebServiceClientException;
import org.springframework.ws.client.support.interceptor.ClientInterceptor;
import org.springframework.ws.context.MessageContext;

/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明：对spring-ws client side 报文记录
 */
public class TracingClientInterceptor implements ClientInterceptor {
	
	protected Logger log = LoggerFactory.getLogger(TracingClientInterceptor.class);
	
	public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream(64);
		try {
			if(messageContext.getRequest() == null){
				return true ;
			}
			
			messageContext.getRequest().writeTo(baos);
			this.log.debug(">>>>>> Client Send Request [" + new String(baos.toByteArray()) + "]");
			
			messageContext.setProperty("SendTime", Long.valueOf(System.currentTimeMillis()));
			
		} catch (IOException e) {
			this.log.error("Error write to output stream . " , e);
		}
		
		return true ;
	}
	
	public boolean handleResponse(MessageContext messageContext) throws WebServiceClientException {
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream(64);
		try {
			if(messageContext.getResponse() == null){
				return true ;
			}
			
			messageContext.getResponse().writeTo(baos);
			
			if(messageContext.getProperty("SendTime") != null){
				long disTime = System.currentTimeMillis() - ((Long)messageContext.getProperty("SendTime")).longValue() ;
				this.log.debug(">>>>>>>>Client Receive Response [" + new String(baos.toByteArray()) + "] , Elapsed Time [" + disTime + "] ms.");
				return true ;
			}
			
			this.log.debug(">>>>>>Client Receive Response [" + new String(baos.toByteArray()) + "] , elapsed Time Not Available.");
			
		} catch (IOException e) {
			this.log.error("Error write to output stream . " , e);
		}
		
		return true ;
	}
	
	
	public boolean handleFault(MessageContext messageContext) throws WebServiceClientException {
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream(64);
		try {
			
			if(messageContext.getResponse() == null){
				return true ;
			}
			
			messageContext.getResponse().writeTo(baos);
			
			if(messageContext.getProperty("SendTime") != null){
				long disTime = System.currentTimeMillis() - ((Long)messageContext.getProperty("SendTime")).longValue();
				this.log.debug(">>>>>Client Receive Fault [" + new String(baos.toByteArray()) + "]. Elapsed Time [" + disTime + "] ms.");
				
				return true ;
			}
			
			this.log.debug(">>>>>Client Receive Fault [" + new String(baos.toByteArray()) + "] . Elapsed Time not Available.");
		} catch (IOException e) {
			this.log.error("Error write to output stream . " , e);
		}
		
		return true ;
	}
	
}
